package com.ruoyi.web.controller.pack;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pack.domain.PackLocator;
import com.ruoyi.pack.service.IPackLocatorService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 定位器Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/pack/locator")
public class PackLocatorController extends BaseController
{
    @Autowired
    private IPackLocatorService packLocatorService;

    /**
     * 查询定位器列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/list")
    public TableDataInfo list(PackLocator packLocator)
    {
        startPage();
        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);
        return getDataTable(list);
    }

    /**
     * 导出定位器列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:export')")
    @Log(title = "定位器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PackLocator packLocator)
    {
        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        util.exportExcel(response, list, "定位器数据");
    }

    /**
     * 获取定位器详细信息
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:query')")
    @GetMapping(value = "/{locatorId}")
    public AjaxResult getInfo(@PathVariable("locatorId") Long locatorId)
    {
        return success(packLocatorService.selectPackLocatorByLocatorId(locatorId));
    }

    /**
     * 新增定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:add')")
    @Log(title = "定位器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PackLocator packLocator)
    {
        // 校验定位器编码唯一性
        if (!packLocatorService.checkLocatorCodeUnique(packLocator.getLocatorCode()))
        {
            return error("新增定位器'" + packLocator.getLocatorCode() + "'失败，定位器编码已存在");
        }
        
        return toAjax(packLocatorService.insertPackLocator(packLocator));
    }

    /**
     * 修改定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:edit')")
    @Log(title = "定位器", businessType = BusinessType.UPDATE)
    @PutMapping("/{locatorId}")
    public AjaxResult edit(@PathVariable("locatorId") Long locatorId, @RequestBody PackLocator packLocator)
    {
        packLocator.setLocatorId(locatorId);
        return toAjax(packLocatorService.updatePackLocator(packLocator));
    }

    /**
     * 删除定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:remove')")
    @Log(title = "定位器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{locatorIds}")
    public AjaxResult remove(@PathVariable Long[] locatorIds)
    {
        return toAjax(packLocatorService.deletePackLocatorByLocatorIds(locatorIds));
    }

    /**
     * 更新定位器状态
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:status')")
    @Log(title = "更新定位器状态", businessType = BusinessType.UPDATE)
    @PutMapping("/{locatorId}/status")
    public AjaxResult updateStatus(@PathVariable("locatorId") Long locatorId, @RequestBody UpdateStatusRequest request)
    {
        return toAjax(packLocatorService.updateLocatorStatus(locatorId, 
            request.getLocatorStatus(), request.getBatteryLevel(), request.getSignalStrength()));
    }

    /**
     * 查询未绑定器具的定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/unbound")
    public AjaxResult getUnboundLocators()
    {
        List<PackLocator> list = packLocatorService.selectUnboundLocators();
        return success(list);
    }

    /**
     * 查询已绑定器具的定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/bound")
    public AjaxResult getBoundLocators()
    {
        List<PackLocator> list = packLocatorService.selectBoundLocators();
        return success(list);
    }

    /**
     * 获取定位器选项列表（用于下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/options")
    public AjaxResult getLocatorOptions()
    {
        // 查询定位器列表
        PackLocator packLocator = new PackLocator();
        packLocator.setLocatorStatus("1"); // 只查询状态正常的定位器
        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);
        
        // 转换为选项格式
        List<Map<String, Object>> options = new ArrayList<>();
        for (PackLocator locator : list) {
            Map<String, Object> option = new HashMap<>();
            option.put("value", locator.getLocatorId());
            option.put("label", locator.getLocatorCode());
            
            // 添加绑定的器具信息
            if (locator.getBoundContainer() != null) {
                option.put("containerId", locator.getBoundContainer().getContainerId());
                option.put("containerCode", locator.getBoundContainer().getContainerCode());
                option.put("materialCode", locator.getBoundContainer().getMaterialCode());
                option.put("materialName", locator.getBoundContainer().getMaterialName());
            }
            
            options.add(option);
        }
        
        return success(options);
    }

    /**
     * 根据定位器编码查询定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:query')")
    @GetMapping("/code/{locatorCode}")
    public AjaxResult getByCode(@PathVariable("locatorCode") String locatorCode)
    {
        return success(packLocatorService.selectPackLocatorByLocatorCode(locatorCode));
    }

    /**
     * 检查定位器编码唯一性
     */
    @GetMapping("/checkLocatorCodeUnique")
    public AjaxResult checkLocatorCodeUnique(String locatorCode)
    {
        return success(packLocatorService.checkLocatorCodeUnique(locatorCode));
    }

    /**
     * 导入定位器数据
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:import')")
    @Log(title = "定位器", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        List<PackLocator> locatorList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = packLocatorService.importLocator(locatorList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载定位器导入模板
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:import')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        util.importTemplateExcel(response, "定位器数据");
    }

    /**
     * 更新定位器状态请求体
     */
    public static class UpdateStatusRequest {
        private String locatorStatus;
        private Long batteryLevel;
        private Long signalStrength;

        public String getLocatorStatus() {
            return locatorStatus;
        }

        public void setLocatorStatus(String locatorStatus) {
            this.locatorStatus = locatorStatus;
        }

        public Long getBatteryLevel() {
            return batteryLevel;
        }

        public void setBatteryLevel(Long batteryLevel) {
            this.batteryLevel = batteryLevel;
        }

        public Long getSignalStrength() {
            return signalStrength;
        }

        public void setSignalStrength(Long signalStrength) {
            this.signalStrength = signalStrength;
        }
    }
} 